/* define some key to save local store */
var strRefreshTokenKey  = "strRefreshTokenKey";
var strAccessTokenKey   = "strAccessTokenKey";

var strIsLoginKey       = "strIsLoginKey";

var strSettingStringKey = "strSettingStringKey";


var strClientId         = "getabstract-mobile-native-app";
var strClientSecrect    = "sYMPTJpnIprDGQAh";
var strAuthorization    = Base64.encode(strClientId + ':' + strClientSecrect);




// Check session expire after call API
// + listEntity	: list of return objects
// + isCheckLength : Notify message when length of list = 0
// + expire : callback to process expired
// + continute : callback to process next 
function CheckExpireSession(listEntity, isCheckLength, expire, continute)
{
	// Check length of return list
	if (listEntity().length > 0) {
		var entityTemp = new ko.observable();
		/* have data return from server */
		entityTemp(listEntity()[0]);
		// [TODO] Move to new function: check expire session
		if (entityTemp().responseCode() != 0) {
			/* get error from server */
			if (entityTemp().responseCode() == expireSessionCode) {
				/* expire session handle */
				sessionVM.appRenewSession(function (status) {
					if (status == true) {
                        expire();
                    } else {
                        /* show message here */
                        stopLoading();
                        /* get session again failed */
                        model.viewLoginInfoWhenExpire();
                    }
				});
			} else {
				stopLoading();
                if (entityTemp().displayError()){
                    showPopup(entityTemp().errorMessage());
                }
				
			}
		} else {
			// Only hide loading for NONE background process (~ NOT show error message)
			if (isCheckLength) {
				hideLoadingDialog();
				
			}
            isLoading = false;
			continute(entityTemp().object);
		}
        
	}
    
}
function CheckExpireSessionErrorCallback(entity, expire, notExpire)
{
	// Check length of return list
	/* expire session handle */
    if (entity.responseText != undefined && entity.responseText != ''){
        var responseText = null;
        try{
            responseText = $.parseJSON(entity.responseText);
        }
        catch(e){
            stopLoading();
            notExpire();
            
            if (entity.statusText != undefined && entity.statusText != ''){
                ShowErrorMessage(entity.statusText);
            }
            else{
                /* show default message */
                ShowErrorMessage();
            }
            return;
        }
        if (responseText.error != undefined && responseText.error == 'invalid_token'){
            /* expire token, send request get token again */
            sessionVM.appRenewSession(function (status) {
                                      if (status == true) {
                                      /* get token again success */
                                          expire();
                                      } else {
                                          /* show message here */
                                          stopLoading();
                                          /* get session again failed */
                                          model.viewLoginInfoWhenExpire();
                                      }
                                      });
        }
        else{
            stopLoading();
            notExpire();
            /* show error */
            if (responseText.error_description != undefined && responseText.error_description != ''){
                ShowErrorMessage(responseText.error_description);
            }
            else{
                /* show default message */
                ShowErrorMessage();
            }
        }
    }
    else{
        stopLoading();
        notExpire();
        /* show default message */
        ShowErrorMessage();
    }
}
// Check pre-condition before loading
// + check internet connections
// + checkMultipleClick: check multiple click (touch)
// + checkLoading: check current loading task
// + checkToken: check currrent token
function CanLoad()
{
//	if (navigator.connection.type == Connection.NONE) {
//		showPopup(getLocalizeText("internetConnectionRequired"));
//		return false;
//	}

	if (isJqmGhostClick())
		return false;

	if (isLoading)
		return false;

	return true;
}

// Reset local storage
function ResetLocalStorage() {
	var domainString = localStore.get(strDomainKey);
	var lastRating = localStore.get("wasrated");
	var theFirstTime = localStore.get("firstStartNewAPI");
	window.localStorage.clear();
	localStore.save("firstStartNewAPI", theFirstTime);
	localStore.save("wasrated", lastRating);
	localStore.save(strDomainKey, domainString);
	localStore.deleteDirectory();
}

// Save book to local
function SaveBookToLocal(folder, bookId, content) {
	if (localStore.get(folder) == null) {
		localStore.save(folder, ko.toJSON(content));
	} else {
		var overViewsJSON = localStore.get(folder);
		var overViews = JSON.parse("[" + overViewsJSON + "]");
		overViewsJSON = "";
		var isExist = false;
		_.each(overViews, function (i) {
			if (i.dataId == bookId) {
				isExist = true;
				i.status = "";
			}
			overViewsJSON = overViewsJSON + ko.toJSON(i) + ",";
		});
		if (isExist) {
			overViewsJSON = overViewsJSON.substring(0, overViewsJSON.length - 1);
		} else {
			overViewsJSON = overViewsJSON + ko.toJSON(content);
		}
		localStore.save(folder, overViewsJSON);
	}
}
// Save book to local
function SaveBookToLocalFirstPosition(folder, bookId, content) {
	if (localStore.get(folder) == null) {
		localStore.save(folder, ko.toJSON(content));
	} else {
		var overViewsJSON = localStore.get(folder);
		var overViews = JSON.parse("[" + overViewsJSON + "]");
		overViewsJSON = "";
		_.each(overViews, function (i) {
               if (i.dataId != bookId) {
                   if (overViewsJSON == ""){
                   /* is first item */
                   overViewsJSON = ko.toJSON(i);
                   }
                   else{
                   overViewsJSON = overViewsJSON + "," + ko.toJSON(i);
                   }
               }
               
               });
		overViewsJSON = ko.toJSON(content) + "," + overViewsJSON;
		localStore.save(folder, overViewsJSON);
	}
}
// Error message
function ShowErrorMessage(strErrorMessage) {
	hideLoadingDialog();
	isLoading = false;
    if (strErrorMessage != undefined){
        showPopup(strErrorMessage);
    }
    else{
        showPopup(getLocalizeText("somethingWentWrong"));
    }
	
}
// Stoploading
function stopLoading() {
	hideLoadingDialog();
	isLoading = false;
}